package com.lp.typeHandler;

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

/**
 *   以javaType为Integer数组和jdbcType为null注册了一个IntegerArrayTypeHandler
 *
 */
@MappedTypes({Integer[].class})  
//@MappedJdbcTypes({JdbcType.ARRAY,JdbcType.NULL})
public class IntegerArrayTypeHander implements TypeHandler<Integer[]> {

	@Override
	public void setParameter(PreparedStatement ps, int i, Integer[] parameter,
			JdbcType jdbcType) throws SQLException {
		// TODO Auto-generated method stub
		Connection con = ps.getConnection();
        // hack: if using poolable connection from dbcp must get inside true connection! 
        if(con instanceof org.apache.commons.dbcp2.PoolableConnection ) {
            con =     ((org.apache.commons.dbcp2.PoolableConnection)con).getInnermostDelegate();
        }
        if(parameter!=null){
        	 Array array = con.createArrayOf("integer", parameter);
             ps.setArray(i,array);
        }else
        	ps.setArray(i, null);
	}

	@Override
	public Integer[] getResult(ResultSet rs, String columnName)
			throws SQLException {
		// TODO Auto-generated method stub
		Array array = rs.getArray(columnName);
	    if (array != null) {
	    	Object[] arr=(Object[])array.getArray();
	    	Integer[] data=new Integer[arr.length];
	    	for (int i=0;i<arr.length;i++) {
				data[i]=(Integer) arr[i];
			}
	      return data;
	    }
		return null;
	}

	@Override
	public Integer[] getResult(ResultSet rs, int columnIndex)
			throws SQLException {
		// TODO Auto-generated method stub
		Array array = rs.getArray(columnIndex);
	    if (array != null) {
	    	Object[] arr=(Object[])array.getArray();
	    	Integer[] data=new Integer[arr.length];
	    	for (int i=0;i<arr.length;i++) {
				data[i]=(Integer) arr[i];
			}
	      return data;
	    }
		return null;
	}

	@Override
	public Integer[] getResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		// TODO Auto-generated method stub
		Array array = cs.getArray(columnIndex);
	    if (array != null) {
	    	Object[] arr=(Object[])array.getArray();
	    	Integer[] data=new Integer[arr.length];
	    	for (int i=0;i<arr.length;i++) {
				data[i]=(Integer) arr[i];
			}
	      return data;
	    }
		return null;
	}

	
	

	
}
